const myRequest = require('../../utils/request.js'); // 导入整个模块
const app = getApp()
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '../../store/strategy/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 0,
    daily: [],
    datesWeeks: [],
    active: 0,
    activeindex: 0, //当前天气预报日期下标,
    city: '广州', //显示当前定位城市
    province: '广东省',
    strategy: [],
    timedata: [],
    showdata: [],
    topHeight:0
  },

  // 滚动事件监听
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop,
    })
  },
  onShow() {
    store.updatestrategy({})
    this.getdateweek()
    this.getweather()
    this.onLocation()
    this.getstrategy()
    
  },
  onLoad(options) {
    // this.getdateweek()
    // this.getweather()
    // this.onLocation()
    // this.getstrategy()
    const { statusBarHeight } = wx.getSystemInfoSync();
    this.setData({
      topHeight: statusBarHeight + 40
    })
    //在onload中创建
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['strategy'],
      actions: ['updatestrategy']
    })
  },

  getstrategy() {
    let that = this
    myRequest.get('/strategy/strategydata', {}).then(res => {
      // if (!res.data.status) {
      const strategy = res.data.map(item => ({
        ...item,
        avatar: app.globalData.baseAPI + item.avatar
      }))
      // 遍历数组A中的每个对象B
      strategy.forEach((item) => {
        item.collect = JSON.parse(item.collect)
        item.like = JSON.parse(item.like)
      })
      const showdata = [...strategy]
      const timedata = [...strategy]
      showdata.sort((a, b) => (b.averageLikeValue) - (a.averageLikeValue))
      timedata.sort((a, b) => {
        // 将日期字符串转换为日期对象并获取时间戳进行比较
        const dateA = new Date(a.date).getTime();
        const dateB = new Date(b.date).getTime();

        // 按日期的降序排列
        return dateB - dateA;
      });
      that.setData({
        timedata: timedata.slice(0, 10),
        showdata: showdata.slice(0, 10)
      })
    }).catch(err => {
      console.error(err);
    });
    
  },
  replaceSpecialChar(content) {

    var regex = new RegExp('<img', 'gi')
    var delImgStyleReg = /(?<=\" )style=\".*?\"/gi;
    content = content.replace(delImgStyleReg, '')
    content = content.replace(regex, '<img style="width: 100%  !important";height:"auto  !important"')
    return content;

  },
  //攻略详情
  toastrategy(e) {
    const data = e.currentTarget.dataset.item
    data.islove = false
    data.iscollect = false
    let username = JSON.parse(wx.getStorageSync('userinfo')).username
    data.content = this.replaceSpecialChar(data.content)
    data.tag = JSON.parse(data.tag)
    data.comment = JSON.parse(data.comment)
    data.like.forEach((element, index) => {
      if (username == element.username) {
        data.islove = true
      }
    });
    data.collect.forEach((element, index) => {
      if (username == element.username) {
        data.iscollect = true
      }
    });

    store.updatestrategy(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: '/packagesB/pages/astrategy/index',
    })
  },
  // 格式化日期为 yyyy-MM-dd 格式
  formatDate(date) {
    let m = (date.getMonth() + 1).toString().padStart(2, '0');
    let d = date.getDate().toString().padStart(2, '0');
    return `${m}/${d}`;
  },

  // 获取星期几
  getWeekday(date) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[date.getDay()];
  },
  getdateweek() {
    const datesWeek = []
    //计算天数
    // 创建一个函数来获取指定天数后的日期和星期几
    // 填充数组对象
    datesWeek.push({
      date: this.formatDate(new Date()),
      week: this.getWeekday(new Date())
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 2 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 2 * 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 4 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 4 * 24 * 60 * 60 * 1000))
    }, );
    this.setData({
      datesWeeks: datesWeek
    })

  },
  getweather() {
    let that = this
    myRequest.get('/get/weatherdata', {key: this.data.city}).then(res=>{
      that.setData({
        daily: res.data.daily
      })
    })
   
  },

  //标签改变时
  onChange(event) {
    this.setData({
      active: event.detail.name
    })
  },

  //点击日期时
  clickdate(e) {
    this.setData({
      activeindex: e.currentTarget.dataset.activeindex
    })
  },

  //逆地址解析
  async getcity() {

    let that = this
    // 如果用户更新授权信息，则调用 getLocation 获取用户地理位置信息
    const res = await wx.getLocation()
    let {
      longitude,
      latitude
    } = res;
    wx.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
      method: 'GET',
      data: {
        key: '3a2e1f6885f7056042443f10052b418d',
        location: longitude + "," + latitude
      },
      success(res) {
        //  console.log(res.data.regeocode.addressComponent.city);
        that.setData({
          city: res.data.regeocode.addressComponent.city,
          province: res.data.regeocode.addressComponent.province
        })
        app.globalData.city = res.data.regeocode.addressComponent.province
        that.getweather()

      }
    })
  },

  // 获取用户地理位置信息
  async onLocation() {
    let that = this
    // 调用 getSetting 方法获取用户所有的授权信息
    // 返回的 authSetting 包含小程序已向小程序申请过的权限已经授权结果(true、false)
    const {
      authSetting
    } = await wx.getSetting()

    // scope.userLocation 是否已经授权获取地理位置的信息
    // 如果之前没有申请过返回 undefined，需要调用 getLocation
    // 如果之前同意了授权，返回 true，需要调用 getLocation
    // 如果之前拒绝了授权，返回 false，需要用户手动进行授权
    // 等于 true，或者不等于 undefined，说明需要进行授权
    // const isAuth =
    //   authSetting['scope.userLocation'] ||
    //   authSetting['scope.userLocation'] === undefined

    // 为了避免冗余的条件判断，使用 !! 把代码进行优化
    const isAuth = !!authSetting['scope.userLocation']

    if (!isAuth) {
      // 弹窗询问用户是否进行授权

      wx.showModal({
        title: '授权提示',
        content: '需要您的地理位置信息，请确认授权',
        async success(res) {
          if (res.confirm) {
            that.getcity()
          } else if (res.cancel) {
            return wx.showToast({
              title: '您拒绝了授权',
              icon: 'error',
              duration: 2000
            })
          }
        }
      })



    } else {
      try {
        // 如果是第一次调用 getLocation 或者之前授权过
        // 直接调用 getLocation 获取用户信息即可
        that.getcity()
      } catch (error) {
        wx.showToast({
          title: '您拒绝授权获取地址位置',
          icon: 'error',
          duration: 2000
        })
      }
    }
  },

  



})